﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using Ron.PhoneTest.Attr;
using Ron.PhoneTest.Tools;

namespace Ron.PhoneTest
{
    public class Startup
    {
        public Startup(IConfiguration configuration, IHostingEnvironment env)
        {
            Configuration = configuration;

            JsonConvert.DefaultSettings = () =>
            {
                //json格式是否需要格式化.默认不格式化.
                var st = new JsonSerializerSettings
                {
                    Formatting = Formatting.None
                };

                st.Converters.Add(new BooleanConverter());
                st.Converters.Add(new DateTimeConverter());
                st.ContractResolver = new LowercaseContractResolver();
                return st;
            };
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);


            services.AddScoped<ModelValidationAttribute>();
            CreatePhoneValidator(services);
        }

        private void CreatePhoneValidator(IServiceCollection services)
        {
            Hashtable segment = new Hashtable();
            var coll = Configuration.GetSection("phone-segment").GetChildren();
            foreach (var prefix in coll)
            {
                if (string.IsNullOrEmpty(prefix.Value))
                    continue;
                foreach (var s in prefix.Value.Split(','))
                    segment[s] = s;
            }
            var pv = new PhoneValidator(segment);
            services.AddSingleton(pv);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseMvc();
            app.UseHttpsRedirection();
            
        }
    }
}
